package com.demo.app.service.department;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.app.mapper.department.DepartmentMapper;
import com.demo.app.mapper.user.UserMapper;
import enums.ErrorCodeEnum;
import model.dto.del.BatchDeleteDto;
import model.dto.department.InsertDepartmentDto;
import model.dto.department.UpdateDepartmentDto;
import model.entity.sys.SysUser;
import model.entity.department.SysDepartment;
import model.vo.department.DepartmentDetailVo;
import model.vo.department.DepartmentListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.CommonConstants;
import result.Result;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: fire_control
 * @description:
 * @author: fbl
 * @create: 2021-04-01 09:55
 **/
@Service
public class DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    UserMapper userMapper;

    public Result departmentList() {
        QueryWrapper<SysDepartment> sysDepartmentQueryWrapper = new QueryWrapper<SysDepartment>().eq("is_delete", 0);
        List<SysDepartment> departments = departmentMapper.selectList(sysDepartmentQueryWrapper);
        List<DepartmentListVo> deptListVo = getDeptListVo(departments);

        // 双重for找子集
        for (DepartmentListVo departmentListVo : deptListVo) {
            ArrayList<DepartmentListVo> departmentListVos = new ArrayList<>();
            for (DepartmentListVo departmentListVo2 : deptListVo) {
                if (departmentListVo2.getFatherId().equals(departmentListVo.getId())) {
                    departmentListVos.add(departmentListVo2);
                }
            }
            departmentListVo.setDepartmentVos(departmentListVos);
        }

        // 删去不是最大级别的
        deptListVo.removeIf(e -> e.getFatherId() != 0);
        // 置入部门级别
        setDepartmentGrade(deptListVo, 0);
        return Result.success(deptListVo);
    }

    /**
     * 置入部门级别，方便前端树状展示
     *
     * @param deptListVo
     */
    private void setDepartmentGrade(List<DepartmentListVo> deptListVo, Integer grade) {
        if (CollectionUtil.isNotEmpty(deptListVo)) {
            grade++;
            for (DepartmentListVo departmentListVo : deptListVo) {
                departmentListVo.setDepartmentGrade(grade);
                // 递归调用
                setDepartmentGrade(departmentListVo.getDepartmentVos(),grade);
            }
        }
    }

    /**
     * 部门列表模型转换
     *
     * @param departments
     * @return
     */
    private List<DepartmentListVo> getDeptListVo(List<SysDepartment> departments) {
        ArrayList<DepartmentListVo> departmentListVos = new ArrayList<>();
        DepartmentListVo departmentListVo;
        for (SysDepartment department : departments) {
            departmentListVo = new DepartmentListVo();
            BeanUtils.copyProperties(department, departmentListVo);
            departmentListVos.add(departmentListVo);
        }
        return departmentListVos;
    }

    public Result departmentDetail(Integer id) {
        DepartmentDetailVo departmentDetailVo = new DepartmentDetailVo();
        QueryWrapper<SysDepartment> sysDepartmentQueryWrapper = new QueryWrapper<SysDepartment>().eq("is_delete", 0).eq("id", id);
        SysDepartment sysDepartment = departmentMapper.selectOne(sysDepartmentQueryWrapper);
        BeanUtils.copyProperties(sysDepartment, departmentDetailVo);

        return Result.success(departmentDetailVo);
    }

    public Result updateDepartment(UpdateDepartmentDto updateDepartmentDto) {
        if (!isUniqueDeptName(updateDepartmentDto.getDepartmentName())) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_DEPT_REPETITION);
        }
        SysDepartment sysDepartment = new SysDepartment();
        BeanUtils.copyProperties(updateDepartmentDto, sysDepartment);
        departmentMapper.updateById(sysDepartment);
        return Result.success();
    }

    public Result addDepartment(InsertDepartmentDto insertDepartmentDto) {
        if (!isUniqueDeptName(insertDepartmentDto.getDepartmentName())) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_DEPT_REPETITION);
        }
        SysDepartment sysDepartment = new SysDepartment();
        BeanUtils.copyProperties(insertDepartmentDto, sysDepartment);
        departmentMapper.insert(sysDepartment);
        return Result.success();
    }

    public Result delDepartment(BatchDeleteDto batchDeleteDto) {
        List<Integer> ids = batchDeleteDto.getIds();
        // 如果部门中有人员，不能删除
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.in("department_id", ids);
        List<SysUser> sysUsers = userMapper.selectList(sysUserQueryWrapper);
        if (CollectionUtil.isNotEmpty(sysUsers)) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_DEPT_DELETE);
        }
        int res = departmentMapper.deleteBatchIds(ids);
        if (res == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_DELETE_FAILED);
        }
        return Result.success();
    }

    /**
     * @return
     * @Author fbl
     * @Description 部门名称不能重复
     * @Date 10:24 2021/4/1
     * @Param
     */
    private boolean isUniqueDeptName(String name) {
        QueryWrapper<SysDepartment> sysDepartmentQueryWrapper = new QueryWrapper<SysDepartment>().eq("is_delete", 0).eq("department_name", name);
        List<SysDepartment> departments = departmentMapper.selectList(sysDepartmentQueryWrapper);
        return CollectionUtil.isEmpty(departments);
    }
}
